package com.graduation.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.common.domain.dto.PageDTO;
import com.graduation.common.exceptions.BizException;
import com.graduation.mapper.FavoriteMapper;
import com.graduation.pojo.po.Case;
import com.graduation.pojo.po.Favorite;
import com.graduation.pojo.po.LegalDocument;
import com.graduation.pojo.po.User;
import com.graduation.pojo.dto.FavoriteToggleDTO;
import com.graduation.pojo.query.FavoriteQuery;
import com.graduation.pojo.vo.FavoriteVO;
import com.graduation.service.CaseService;
import com.graduation.service.FavoriteService;
import com.graduation.service.LegalDocumentService;
import com.graduation.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements FavoriteService {

    private final UserService userService;

    private final LegalDocumentService legalDocumentService;

    private final CaseService caseService;

    @Override
    public PageDTO<FavoriteVO> pageFavorites(FavoriteQuery query) {
        // 使用自定义SQL进行联查
        Page<FavoriteVO> page = new Page<>(query.getPageNum(), query.getPageSize());
        Page<FavoriteVO> result = baseMapper.selectFavoriteVOPage(page, query);
        
        return PageDTO.of(result.getPages(), result.getTotal(), result.getRecords());
    }

    @Override
    public void toggleFavorite(FavoriteToggleDTO dto) {
        // 验证用户是否存在
        User user = userService.getById(dto.getUserId());
        if (user == null) {
            throw new BizException("用户不存在");
        }

        // 必须收藏文档或案件其中之一
        if (dto.getDocumentId() == null && dto.getCaseId() == null) {
            throw new BizException("必须指定收藏的文档或案件");
        }

        // 不能同时收藏文档和案件
        if (dto.getDocumentId() != null && dto.getCaseId() != null) {
            throw new BizException("不能同时收藏文档和案件");
        }

        Favorite existingFavorite = null;

        // 检查文档收藏状态
        if (dto.getDocumentId() != null) {
            // 验证文档是否存在
            LegalDocument document = legalDocumentService.getById(dto.getDocumentId());
            if (document == null) {
                throw new BizException("关联的法律文档不存在");
            }

            // 查找现有收藏记录
            existingFavorite = lambdaQuery()
                    .eq(Favorite::getUserId, dto.getUserId())
                    .eq(Favorite::getDocumentId, dto.getDocumentId())
                    .one();
        }

        // 检查案件收藏状态
        if (dto.getCaseId() != null) {
            // 验证案件是否存在
            Case caseEntity = caseService.getById(dto.getCaseId());
            if (caseEntity == null) {
                throw new BizException("关联的案件不存在");
            }

            // 查找现有收藏记录
            existingFavorite = lambdaQuery()
                    .eq(Favorite::getUserId, dto.getUserId())
                    .eq(Favorite::getCaseId, dto.getCaseId())
                    .one();
        }

        if (existingFavorite != null) {
            // 已收藏，执行取消收藏
            removeById(existingFavorite.getId());
            log.info("用户{}取消收藏，收藏ID：{}", dto.getUserId(), existingFavorite.getId());
        } else {
            // 未收藏，执行收藏
            Favorite favorite = new Favorite();
            favorite.setUserId(dto.getUserId());
            favorite.setDocumentId(dto.getDocumentId());
            favorite.setCaseId(dto.getCaseId());
            save(favorite);
            log.info("用户{}添加收藏，文档ID：{}，案件ID：{}", dto.getUserId(), dto.getDocumentId(), dto.getCaseId());
        }
    }

    @Override
    public Boolean checkFavorite(Long userId, Long documentId, Long caseId) {
        // 参数验证
        if (documentId == null && caseId == null) {
            throw new BizException("必须指定查询的文档或案件");
        }
        if (documentId != null && caseId != null) {
            throw new BizException("不能同时查询文档和案件的收藏状态");
        }

        // 构建查询条件
        var queryWrapper = lambdaQuery().eq(Favorite::getUserId, userId);
        
        if (documentId != null) {
            queryWrapper.eq(Favorite::getDocumentId, documentId);
        }
        
        if (caseId != null) {
            queryWrapper.eq(Favorite::getCaseId, caseId);
        }

        // 返回是否存在
        return queryWrapper.exists();
    }

}
